from django.shortcuts import render
from django.http import HttpResponse
# 导入api接口相关模块
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.core import serializers
# Create your views here.
from .models import userInfo

#查询数据
def is_exist(username: str)->list:
    return userInfo.objects.filter(username=username)

#注册用户
def add_user(request):
    # 将要返回的对象
    response = {}
    if request.method == 'GET' and request.GET:
        userName, password = request.GET['username'], request.GET['password']
        try:
            #创建用户数据
            user = userInfo(userName, password)
            #是否已存在
            if is_exist(userName):
                response['msg'] = "用户名已存在！"
                response['status'] = 409
            else:
                #将用户数据添加到数据库中
                user.save()
                response['msg'] = "success"
                response['status'] = 200
        except Exception as e:
            response['msg'] = str(e)
            response['status'] = 406
            #向前端返回结果
        return JsonResponse(response)
#用户登录
def user_login(request):
    response = {}
    if request.method == 'GET' and request.GET:
        username,password = request.GET['username'],request.GET['password']
        #接收数据库查询的结果
        result = is_exist(username)
        #判断用户名密码是否对应
        if(result and result[0].password == password):
            response['msg'] = 'success'
            response['status'] = 200
        else:
            response['msg'] = '用户名或密码错误'
            response['status'] = 400
        
        
    return JsonResponse(response)